/*
 * base模块
 * @author li.xiaomei
 * @date 2016-09-29
 */
var SuperClass = require('./class');
var Event = require('./event');
var tempalteModule = require('./template');


var Base = SuperClass.extend(Event, {
  EVENTS: {},
  template: '',
  init: function(config) {
    this._config = config;

    this.bind();
    this._delegateEvent();
    this.render();
  },

  get: function(key) {
    return this._config[key];
  },

  set: function(key, value) {
    this._config[key] = value;
  },

  _delegateEvent: function() {
    var self = this,
      events = self.EVENTS || {},
      eventObjs, fn, select, type;

    var parentNode = self.get('parentNode') || $(document.body);

    for (select in events) {
      eventObjs = events[select];

      for (type in eventObjs) {
        fn = eventObjs[type];

        parentNode.delegate(select, type, fn);
      }
    }

  },

  _parseTemplate: tempalteModule,

  //提供给子类覆盖实现
  setUp: function() {
    this.render();
  },

  bind: function() {},

  render: function(data) {
    var self = this;
    self.set('_currentData', data);

    if (!self.template) return;

    var html = self._parseTemplate(self.template, data);

    var parentNode = this.get('parentNode') || $(document.body);

    var currentNode = $(html);

    self.set('_currentNode', currentNode);
    parentNode.append(currentNode);
  },

  destroy: function() {
    var self = this;
    //去掉自身的事件监听
    self.off();
    //删除渲染好的dom节点
    self.get('_currentNode').remove();

    //去掉绑定的代理
    var events = self.EVENTS || {};
    var eventObjs, fn, select, type;
    var parentNode = self.get('parentNode');
    for (select in events) {
      eventObjs = events[select];

      for (type in eventObjs) {
        fn = eventObjs[type];
        parentNode.undelegate(select, type, fn);
      }
    }
  }
});

module.exports = Base;
